class AdminController < ApplicationController
	before_filter :must_be_admin
	def index
		if !Flag.first.nil?
			flag = Flag.first
			@market_up = flag.status
		end
	end
	
	def initiate
		History.delete_all
		Status.delete_all
		Flag.delete_all
		Trigger.delete_all
		Update.delete_all
		stocks = Stock.find(:all)
		for stock in stocks
			status = Status.new(:stock_id => stock.id, :open => 1, :open_now => 0)
			status.save!
		end
		flag = Flag.new(:status => 0, :day => 0)
		flag.save!
		graph
		flash[:notice] = 'Market Initiated! Do Sell All NOW!!'
		redirect_to(:controller => 'admin')
	end

	def sell_all
		ownerships = Ownership.find(	:all,
										:conditions => "user_id = 1")
		for ownership in ownerships
			trigger = Trigger.new
			trigger.user_id = 1
			trigger.stock_id = ownership.stock_id
			dummy, trigger.price = Ownership.details(ownership.stock_id)
			trigger.quantity = ownership.quantity
			trigger.action = 'sell'
			trigger.save!
		end
		flash[:notice] = 'Everything you owned has been put up for auction! :P'
		redirect_to(:controller => 'admin')
	end
	def remove
		triggers = Trigger.find(	:all,
									:conditions => "user_id = 1")
		for trigger in triggers
			trigger.destroy
		end
		flash[:notice] = 'Every trigger you set have been removed! :P'
		redirect_to(:controller => 'admin')
	end
	def opening_bell
		Flag.open
		statuses = Status.find(:all) 
		for status in statuses
			if status.open == 1
				status.open_now = 1
			end
			history = History.top(status.stock_id)
			stock = Stock.find(status.stock_id)
			if !history.nil?
				stock.days_opening = history.close
			else
				stock.days_opening = stock.market_value
			end
			stock.save!
			history_new = History.new(:stock_id => status.stock_id, :date => Date.today, :volume => 0)
			history_new.high = history_new.low = history_new.open = stock.market_value
			history_new.save!			
		end		
		engine

		flash[:notice] = 'Ting! Ting! Ting!!'
		redirect_to(:controller => 'admin')
	end
	
	def closing_bell
		Flag.close
		statuses = Status.find(:all) 
		for status in statuses
			if status.open == 1
				status.open_now = 0
			end
			history = History.top(status.stock_id)
			stock = Stock.find(status.stock_id)
			history.close = stock.market_value
			history.save!
		end
		#graph
		flash[:notice] = 'Tong! Tong! Tong!!'
		redirect_to(:controller => 'admin')
	end
	
end
